package com.shuw.com.beingfortextproject.service;

import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;

import java.util.List;

/**
 * Created by ${cs} on 2018/4/13.
 */

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService extends JobService {

	private int JobWakeUpId = 1;

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// 开启轮询
		JobInfo.Builder mJobBuilder = new JobInfo.Builder(JobWakeUpId
		,new ComponentName(this,JobWakeUpService.class));
		// 设置轮询时间
		mJobBuilder.setPeriodic(2000);
		JobScheduler mJobScheduler = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);
		mJobScheduler.schedule(mJobBuilder.build());
		return START_STICKY;
	}

	@Override
	public boolean onStartJob(JobParameters jobParameters) {
		// 开启定是任务 定时轮询 判断应用Service是否被杀死
		// 如果被杀死则重启Service
		boolean messageServiceAlive = serviceAlive(ResidentService.class.getName());
		if (!messageServiceAlive){
			startService(new Intent(this,ResidentService.class));
		}
		return false;
	}

	@Override
	public boolean onStopJob(JobParameters jobParameters) {
		return false;
	}


	private boolean serviceAlive(String serviceName){
		boolean isWork = false;
		ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> list = manager.getRunningServices(100);
		if (list.size()<=0){
			return false;
		}
		int length = list.size();
		for (int i = 0; i < length; i++) {
			String name = list.get(i).service.getClassName().toString();
			if (name.equals(serviceName)){
				isWork = true;
				break;
			}
		}

		return isWork;
	}
}
